package com.springBoot.springBootSysCore.controller;

import com.springBoot.springBootSysCore.common.utils.returnUtil.CodeEnum;
import com.springBoot.springBootSysCore.common.utils.returnUtil.ResultJsonFormat;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Map;

/**
 * 异常信息处理页面
 * @author Administrator
 *
 */
@Controller
@RequestMapping("error")
@EnableConfigurationProperties({ServerProperties.class})
public class SysErrorController extends BasicErrorController {

	public SysErrorController(ErrorAttributes errorAttributes) {
		super(errorAttributes, new ErrorProperties());
	}

	@RequestMapping(produces = "text/html")
	public ModelAndView errorHtml(HttpServletRequest request,
								  HttpServletResponse response) {
		HttpStatus status = getStatus(request);
//		Map<String, Object> model = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.TEXT_HTML));
		Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
		response.setStatus(status.value());
		response.setHeader("Accept","text/html");
		response.setContentType("text/html");
		ModelAndView modelAndView = resolveErrorView(request, response, status, model);
		return (modelAndView == null ? new ModelAndView("error" , model) : modelAndView);
//		/"+status.value() //造成会话丢失 问题未找到
	}
	@Override
	@ResponseBody
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
		Map<String, Object> body = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.ALL));
		HttpStatus status = getStatus(request);
		String msg = "";
		switch (status) {
			case NOT_FOUND:msg = "访问的资源不存在";break;
			case INTERNAL_SERVER_ERROR:msg = "服务器内部出现异常";break;
			case BAD_REQUEST:msg = "参数输入错误";break;
			default:msg="出现其他错误";break;
		}
		ResultJsonFormat rj = new ResultJsonFormat(status.value());
		body.putAll(rj.convertResultJsonForData());
		return new ResponseEntity<Map<String, Object>>(body, status);
	}


}
